<template>
  <div class="app-main">
    <top-nav></top-nav>
    <div class="body">
      <div class="page-container">
        <div class="left-wrapper">
          <ul class="time-wrapper" v-if="state === 'start' || state === 'end'">
            <!-- <li class="item">开始时间：{{ startTimeStr }}</li> -->
            <li class="item">GBA游戏及应对概述</li>
            <li class="item">用时：{{ minute }} </li>
          </ul>
          <div class="exam-box" v-if="state === 'start'">
            <div class="index">第 {{ questionIndex + 1 }} 题</div>
            <div data-v-56628707="" class="mu-badge-container type">
              <em class="mu-badge">{{type}}</em>
            </div>
            <h3 class="title" v-if="question.type !== 'fill'">
              {{ question.content }}
            </h3>
            <div
              class="input"
              v-model="question.userAnswer"
              v-if="question.type === 'aq'">
            </div>
            <div v-if="question.type === 'fill'">
              <span v-for="(content, index) in question._content">
                <div
                  class="fill-input"
                  :style="{ width: content.length * 40 + 'px' }"
                  v-model="question['fill' + content.index]"
                  v-if="content.type === 'blank'">
                </div>
                <!--<input/>-->
                <span v-else>{{ content.text }}</span>
              </span>
            </div>
            <ul class="options" v-if="question.type === 'judgment'">
              <li
                class="item"
                :class="{ selected: isSelected(question, true) }"
                @click="doOption(true)"
              >
                正确
              </li>
              <li
                class="item"
                :class="{ selected: isSelected(question, false) }"
                @click="doOption(false)"
              >
                错误
              </li>
            </ul>
            <ul class="options">
              <li
                class="item"
                v-for="(option, index) in question.options"
                :key="option"
                :class="{ selected: isSelected(question, index) }"
                @click="doOption(index)"
              >
                {{ option }}
              </li>
            </ul>
            <div class="op">
              <el-button
                class="btn"
                @click="prevQuestion"
                :disabled="questionIndex === 0">上一题</el-button>
              <el-button
                class="btn"
                primary
                @click="nextQuestion"
                :disabled="questionIndex === questions.length - 1">下一题</el-button>
              <!--<el-button class="btn" label="查看答案" @click="viewAnswer" :disabled="false" />-->
              <el-button
                class="btn"
                @click="viewAnswer"
                :disabled="false">交卷</el-button>
            </div>
          </div>

          <div class="answer-card" v-if="state === 'end'">
            <h2 class="card-title">答案</h2>
            <div>分数：{{ score }}</div>
            <ul class="answer-list">
              <li
                class="item"
                :class="q.userAnswer == q.answer?'success':'error'"
                v-for="(q, index) in questions"
              >
                <h3 v-if="q.type !== 'fill'">问题：{{ q.content }}</h3>
                <h3 v-if="q.type === 'fill'">
                  问题：{{ getFillContent(q.content) }}
                </h3>
                <h3 v-if="q.type === 'single'">
                  答案：{{ numberToLetter(q.answer) }}. {{ q.options[q.answer] }}
                </h3>
                <h3 v-if="q.type === 'multiple'">
                  答案：
                  <div v-for="answer in q.answer">
                    {{ numberToLetter(answer) }}. {{ q.options[answer] }}
                  </div>
                </h3>
                <h3 v-if="q.type === 'aq'">答案：{{ q.answer }}</h3>
                <h3 v-if="q.type === 'fill'">
                  答案：{{ q.answer.join(", ") }}
                  <!--<div v-for="answer in q.answer">-->
                  <!--{{ answer }}-->
                  <!--</div>-->
                </h3>
                <h3 v-if="q.type === 'judgment'">答案：{{ boolToText(q.answer) }}</h3>

                <div
                  v-if="
                    q.type === 'single' || q.type === 'multiple' || q.type === 'aq'
                  "
                >
                  <div v-if="q.userAnswer || q.userAnswer === 0">
                    <div v-if="q.type === 'single'">
                      你的回答：{{ numberToLetter(q.userAnswer) }}.
                      {{ q.options[q.userAnswer] }}
                    </div>
                    <div v-if="q.type === 'multiple'">
                      你的回答：
                      <div v-for="answer in q.userAnswer">
                        {{ numberToLetter(answer) }}. {{ q.options[answer] }}
                      </div>
                    </div>
                    <div v-if="q.type === 'aq'">你的回答：{{ q.userAnswer }}</div>
                  </div>
                  <div v-else>你还没有回答</div>
                </div>
                <div v-if="q.type === 'fill'">
                  你的回答：{{ getFillUserAnswer(q).join(", ") }}
                </div>
                <div v-if="q.type === 'judgment'">
                  <div v-if="q.userAnswer === true || q.userAnswer === false">
                    你的回答：{{ boolToText(q.userAnswer) }}
                  </div>
                  <div v-else>你还没有回答</div>
                </div>
              </li>
            </ul>
            <el-button class="btn" type="primary" @click="restart">重新测评</el-button>
          </div>
        </div>
        <div class="right-wrapper">
          <div class="simple-answer-card" v-if="state === 'start'">
            <h2 class="card-title">全部试题 <span style="color:#55a532">{{answered}} </span> / {{questions.length}}</h2>
            <ul class="answer-list">
              <li class="item" v-for="(q, index) in questions">
                <el-button
                  class="round-btn unknown"
                  :class="{ finish: isDone(q), current: index === questionIndex }"
                  @click="selectIndex(index)">{{'' + (index + 1)}}</el-button>
              </li>
            </ul>
          </div>
        </div>
      </div>
      <div v-if="state!='end'">
        <el-button @click="pause">暂停</el-button>
        <el-button @click="start">继续</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { format,formatNumber } from "@/util/time";
const FILL = "___";
Array.prototype.contains = function(obj) {
  var i = this.length;
  while (i--) {
    if (this[i] === obj) {
      return true;
    }
  }
  return false;
};
var hour,minute,second;//时 分 秒
hour=minute=second=0;//初始化
export default {
  data() {
    return {
      // exampleFormCode: exampleFormCode,
      // demoCode: demoCode,
      questionIndex: 0,
      /*questions: [
        {
            id: '1',
            type: 'join',
            content: '四大名著连一连',
            leftItems: ['《水浒传》', '《西游记》', '《三国演义》', '《红楼梦》'],
            rightItems: ['罗贯中', '施耐庵', '曹雪芹', '吴承恩'],
            answer: [[0, 1], [1, 3], [2, 0], [4, 2]],
            userAnswer: null
        },
        {
          id: "1",
          type: "judgment",
          content: "所有的苹果都是水果",
          answer: true,
          userAnswer: null
        },
        {
          id: "1",
          type: "fill",
          content: "___秋月何时了，往事___",
          answer: ["春花", "知多少"],
          userAnswer: null
        },
        {
          id: "1",
          type: "aq",
          content: "1+2等于几？",
          answer: "3",
          userAnswer: null
        },
        {
          id: "1",
          type: "multiple",
          content: "哪些是对的",
          options: ["1+1=2", "1+2=3", "1+1=3", "1+2=2"],
          answer: [0, 1],
          userAnswer: null
        },
        {
          id: "1",
          type: "single",
          content: "1+1=?",
          options: ["1", "2", "3", "4"],
          answer: 1,
          userAnswer: null
        }
      ],*/
      questions:[],
      question: {},
      score:0,
      state: "", // 'start', 'end',
      startTime: null,
      endTime: null,
      minute: '00:00:00'
    };
  },
  computed: {
    type() {
      let types = {
        single: "单选题",
        multiple: "多选题",
        fill: "填空题",
        aq: "问答题",
        judgment: "判断题",
        join: "连线题",
        code: "编程题" // Attachment
      };
      return types[this.question.type];
    },
    answered(){
      let answered=0
      this.questions.map((item)=>{
        if(item.userAnswer){
          answered+=1
        }
      })
      return answered
    },
    startTimeStr() {
      return format(new Date(this.startTime), "hh:mm");
    }
  },
  mounted() {
    this.init();
    this.getQuestionList()
    // 测试
    this.start();
  },
  destroyed() {
    clearInterval(this.timer);
  },
  methods: {
    async getQuestionList(){
      let params={
        page: 1,
        limit: 100,
        bank_shop_id: this.$route.params.id
      }
      let {data:{code,data}}=await this.$http.post(this.$api.questionList,params)
      if(code==200){
        data.forEach((item)=>{
          item.content=item.course_title
          item.type='single'
          item.options=new Array()
          item.options[0]=item.course_value_one
          item.options[1]=item.course_value_two
          item.options[2]=item.course_value_three
          item.options[3]=item.course_value_four
          switch(item.course_key) {
            case 'A':
                item.answer=0
                break;
            case 'B':
                item.answer=1
                break;
            case 'C':
                item.answer=2
                break;
            case 'D':
                item.answer=3
                break;
            default:
                break;
          }
        })
        this.questions=data
        this.question = this.questions[this.questionIndex];
      }
    },
    init() {
      for (let question of this.questions) {
        if (question.type === "fill") {
          let content = question.content.replace(
            new RegExp(FILL, "g"),
            "|?|" + FILL + "|?|"
          );
          let arr = content.split("|?|");
          let result = [];
          let blankIndex = 0;
          for (let item of arr) {
            if (item === FILL) {
              result.push({
                type: "blank",
                index: blankIndex,
                length: question.answer[blankIndex].length
              });
              blankIndex++;
            } else {
              result.push({
                type: "text",
                text: item
              });
            }
          }
          question._content = result;
        }
      }
    },
    boolToText(bool) {
      return bool ? "正确" : "错误";
    },
    getFillContent(content) {
      return content.replace(new RegExp(FILL, "g"), "___");
    },
    getFillUserAnswer(question) {
      let answer = [];
      for (let i = 0; i < question.answer.length; i++) {
        if (question["fill" + i]) {
          answer.push(question["fill" + i]);
        } else {
          answer.push(null);
        }
      }
      return answer; // .join(', ')
    },
    isSelected(question, index) {
      if (question.type === "single") {
        return question.userAnswer === index;
      } else if (question.type === "multiple") {
        if (!question.userAnswer) {
          return false;
        }
        for (let answer of question.userAnswer) {
          if (answer === index) {
            return true;
          }
        }
        return false;
      } else if (question.type === "judgment") {
        return question.userAnswer === index;
      }
      return false;
    },
    isSuccess(question) {
      if (question.type !== "fill" && !question.userAnswer) {
        return false;
      }
      if (question.type === "single") {
        return question.userAnswer == question.answer;
      }
      if (question.type === "multiple") {
        // 少选多选不给分
        if (question.answer.length !== question.userAnswer.length) {
          return false;
        }
        for (let i = 0; i < question.answer.length; i++) {
          if (question.answer[i] !== question.userAnswer[i]) {
            return false;
          }
        }
        return true;
      }
      if (question.type === "aq") {
        return question.userAnswer === question.answer;
      }
      if (question.type === "fill") {
        let userAnswer = this.getFillUserAnswer(question);
        if (question.answer.length !== userAnswer.length) {
          return false;
        }
        for (let i = 0; i < question.answer.length; i++) {
          if (question.answer[i] !== userAnswer[i]) {
            return false;
          }
        }
        return true;
      }
      if (question.type === "judgment") {
        return question.userAnswer === question.answer;
      }
      return false;
    },
    isDone(question) {
      if (question.type === "single") {
        return question.userAnswer || question.userAnswer === 0;
      }
      if (question.type === "multiple") {
        return question.userAnswer && question.userAnswer.length;
      }
      if (question.type === "aq") {
        return question.userAnswer;
      }
      if (question.type === "fill") {
        let answer = this.getFillUserAnswer(question);
        for (let item of answer) {
          if (!item) {
            return false;
          }
        }
        return true;
      }
      if (question.type === "judgment") {
        return question.userAnswer === true || question.userAnswer === false;
      }
      return false;
    },
    doOption(index) {
      if (this.question.type === "single") {
        this.questions[this.questionIndex].userAnswer = index;
        // 检查后面是否有未完成的题目
        // for (let i = this.questionIndex + 1; i < this.questions.length; i++) {
        //     if (!this.questions[i].userAnswer) {
        //         this.questionIndex = i
        //         this.question = this.questions[this.questionIndex]
        //         return
        //     }
        // }
        // 检查前面是否有未完成的题目
        // for (let i = 0; i < this.questionIndex; i++) {
        //     if (!this.questions[i].userAnswer) {
        //         this.questionIndex = i
        //         this.question = this.questions[this.questionIndex]
        //         return
        //     }
        // }
        // 所有题答完后自动回到第一题
        this.questionIndex++
        if (this.questionIndex > this.questions.length - 1) {
            this.questionIndex = 0
        }
        this.question = this.questions[this.questionIndex]
      } else if (this.question.type === "multiple") {
        let userAnswer = this.questions[this.questionIndex].userAnswer;
        if (!userAnswer) {
          userAnswer = [];
        }
        if (userAnswer.contains(index)) {
          for (let i = 0; i < userAnswer.length; i++) {
            if (userAnswer[i] === index) {
              userAnswer.splice(i, 1);
              return;
            }
          }
        }
        userAnswer.push(index);
        // 答案排序
        userAnswer = userAnswer.sort();
        console.log(userAnswer)
        this.questions[this.questionIndex].userAnswer = userAnswer;
      } else if (this.question.type === "judgment") {
        this.questions[this.questionIndex].userAnswer = index;
      }
    },
    prevQuestion() {
      this.questionIndex--;
      this.question = this.questions[this.questionIndex];
    },
    selectIndex(index) {
      this.questionIndex = index;
      this.question = this.questions[this.questionIndex];
    },
    nextQuestion() {
      this.questionIndex++;
      this.question = this.questions[this.questionIndex];
    },
    start() {
      console.log(this.timer)
      this.state = "start";
      this.startTime = new Date();
      this.timer = setInterval(this.updateTime, 1000);
    },
    updateTime() {
      // let time = (new Date().getTime() - this.startTime.getTime()) / 1000 / 60;
      // this.minute = time;
      second++;
      if(second>=60){
        second=0;
        minute=minute+1;
      }
      if(minute>=60){
        minute=0;
        hour=hour+1;
      }
      this.minute=formatNumber(hour)+':'+formatNumber(minute)+':'+formatNumber(second);
    },
    pause(){
      if(this.timer){
        clearInterval(this.timer);
      }
    },
    calcScore() {
      let successCount = 0;
      for (let question of this.questions) {
        // if (question.type !== "fill" && !question.userAnswer) {
        //   continue;
        // }
        if (question.type === "single" || question.type === "aq") {
          if (question.userAnswer === question.answer) {
            successCount++;
            this.score=Number(this.score)+Number(question.course_integral)
          }
        }
        /*else if (question.type === "multiple") {
          if (question.answer.length !== question.userAnswer.length) {
            continue;
          }
          let isRight = true;
          for (let i = 0; i < question.answer.length; i++) {
            if (question.answer[i] !== question.userAnswer[i]) {
              isRight = false;
              break;
            }
          }
          if (isRight) {
            successCount++;
          }
        } else if (question.type === "fill") {
          if (this.isSuccess(question)) {
            successCount++;
          }
          console.log("判断", this.isSuccess(question));
        } else if (question.type === "judgment") {
          if (question.userAnswer === question.answer) {
            successCount++;
          }
        }*/
      }
      // this.score = parseInt((100 * successCount) / this.questions.length);
    },
    restart() {
      // 清空回答
      for (let question of this.questions) {
        question.userAnswer = null;
      }
      this.questionIndex = 0;
      this.score=0
      this.start();
    },
    viewAnswer() {
      this.state = "end";
      this.endTime = new Date();
      this.updateTime();
      clearInterval(this.timer);
      this.calcScore()
    },
    numberToLetter(number) {
      let arr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
      return arr[number];
    }
  }
};
</script>

<style lang="scss" scoped>
.app-main {
  min-height: calc(100vh - 50px);
  position: relative;
  overflow: hidden;
  .body {
    width: 80%;
    margin: 20px auto 30px;
    .page-container{
      display: flex;
      .left-wrapper{
        width: 75%;
      }
      .right-wrapper{
        width: 24%;
        margin-left: 1%;
      }
    }
  }
}
.time-wrapper {
  display: flex;
  padding: 20px 30px;
  margin-bottom: 16px;
  background: #ffa400;
  font-size: 20px;
  color: #fff;
  .item {
    flex: 1;
    &:first-child{
      text-align: left;
    }
    &:last-child{
      text-align: right;
    }
  }
}
.simple-answer-card {
  height: 80%;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.117647),
    0 1px 4px rgba(0, 0, 0, 0.117647);
  .card-title {
    font-size: 18px;
    margin-bottom: 16px;
  }
  .answer-list .item {
    float: left;
    margin-right: 16px;
    margin-bottom: 16px;
    font-size: 12px;
    color: #333;
    .round-btn {
      width: 30px;
      height: 30px;
      padding: 0;
      background: #e8e8e8;
      border: none;
      border-radius: 50%;
    }
    .current {
      background: #ffa400;
      color: #fff;
    }
    .finish {
      color: #fff;
      background-color: #55a532;
    }
  }
}
.exam-box {
  padding: 16px;
  margin-bottom: 24px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.117647),
    0 1px 4px rgba(0, 0, 0, 0.117647);
  .index,.mu-badge-container{
    display: inline-block;
  }
  .index{
    margin-right: 10px;
  }
  h3.title {
    padding: 16px;
    margin-bottom: 20px;
    background: #f8f9fb;
    cursor: pointer;
    border: 1px solid #f1f1f1;
    font-size: 16px;
  }
  .type {
    margin-bottom: 16px;
    .mu-badge {
      font-size: 10px;
      display: -webkit-box;
      display: -ms-flexbox;
      display: flex;
      -webkit-box-pack: center;
      -ms-flex-pack: center;
      justify-content: center;
      -webkit-box-align: center;
      -ms-flex-align: center;
      align-items: center;
      padding: 0 6px;
      line-height: 1.5;
      font-size: 12px;
      font-style: normal;
      background-color: #bdbdbd;
      color: #fff;
      border-radius: 3px;
      overflow: hidden;
    }
  }
  .options .item {
    padding: 16px;
    margin-bottom: 4px;
    cursor: pointer;
    border: 1px solid #f1f1f1;
    &.selected {
      border: 1px solid #55a532;
    }
  }
  .op{
    margin-top: 20px;
  }
  .op .btn {
    margin-right: 8px;
  }
}
.answer-card {
  padding: 16px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.117647),
    0 1px 4px rgba(0, 0, 0, 0.117647);
  .answer-card .card-title {
    font-size: 18px;
    margin-bottom: 16px;
  }
  .answer-list .item {
    margin-bottom: 16px;
  }
  .answer-list .item.success {
    border: 1px solid #55a532;
  }
  .answer-list .item.error {
    border: 1px solid #f44;
  }
}
</style>
